<?php
class NewsController extends AppController {
	var $name = 'News';
	var $components = array('Uploader.Uploader');
	var $errors = array();
	//var $uses=array('Image');

	function beforeFilter() {
		parent::beforeFilter();
		$this->Uploader->uploadDir = 'files/uploads/news/'; //thu muc chua file upload
        $this->Uploader->enableUpload = true;
        $this->Uploader->maxFileSize = '2M'; // quy dinh dung luong duoc upload len toi da la 2 Megabytes
        $this->Uploader->maxNameLength = 25;//do dai cua ten file
        $this->Uploader->tempDir = TMP;
		$this->Auth->allow('printpage','send','home','chitiet','pages','listnews','search');
	}
	function home() {
		$this->loadModel('Image','Plan');
		$this->Plan->recursive = 2;
		$imgs=$this->Plan->find('all',array('fields'=>array('id','name','description'),'conditions'=>array('Plan.status'=>2))); 
		$this->set(compact('imgs'));
	}
	function pages($fid=NULL) {
		$this->News->recursive = 1;
		$conds = array('News.status' =>2);
 		if($this->data){
			$key = $this->data['News']['key'];
			$ar1 = array('News.title like' =>'%'.$key.'%');
			$conds = array_merge($conds,$ar1);
		}
		if($fid){
			$ar2 = array('News.catenews_id' => $fid);
			$conds = array_merge($conds,$ar2);
		}
		$this->paginate = array(
			'conditions'=>$conds,
			'limit'=>8,
			'order'=>'News.id DESC'
		);
		$this->set('news', $this->paginate());
	}
	function search($id = null){
		$this->News->recursive = 0;
		$conditions = '';
		$key = $this->data['News']['key'];

		//debug($key);
		if($key!= null){
				$conditions = array('News.title LIKE '=>'%'.$key.'%');
				$this->paginate = array(
				'conditions'=>$conditions,
				'order'=> 'News.id DESC',
				'limit'=>8
			);
			$re_news=$this->paginate();
		}
		else{
			$re_news=null;
		}
		$this->set('re_news',$re_news);
	}
	function listnews($id = null){
		$lists = $this->News->find('all',array('fields'=>array('id','title','shortcontent','image','ngaydang'),'conditions'=>array('News.status'=>2,'catenews_id'=>$id),'limit'=>4,'order'=>'News.id DESC'));
		return $lists;
	}
	function chitiet($id = null) {
  		if (!$id) {
			$this->Session->setFlash(__('Không tồn tại bài viết này.', true));
			$this->redirect(array('action' => 'index'));
		}
		$conditions = array('News.status'=>2);
		$news = $this->News->read(null, $id);
 		$cid = $news['News']['catenews_id'];
 		$this->set('news',$news);
		$othernews = $this->News->find('all',array('conditions'=>array('News.id <>'=>$id,'News.status'=>2,'catenews_id'=>$cid),'limit'=>10,'order'=>'News.id DESC'));
		$this->set(compact('othernews'));
 	}
   	function admin_index() {
		$this->layout='admin';
		$this->News->recursive = 0;
		$conditions = '';
		$cate = $this->data['News']['catenews'];
		$key = $this->data['News']['key'];
 		if($key!= null){
			$conditions = array('News.title LIKE '=>'%'.$key.'%');
		}
		elseif($cate != null){
			$conditions = array('News.catenews_id' => $cate);
		}
		elseif($cate != null && $key!= null){
			$conditions = array( 'News.title LIKE '=>'%'.$key.'%');
		}
		$this->paginate = array(
			'conditions'=>$conditions,
			'order'=> 'News.id DESC'
		);
		$this->set('news', $this->paginate());
		//debug($this->paginate);
		$catenews = $this->News->Catenews->find('list');
		$this->set(compact('catenews','cate','key'));
	}


	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Không tồn tại bài viết này.', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('news', $this->News->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$filename = $this->Uploader->upload('image');
			$this->News->create();
			$users_id = $this->Auth->user('id');
			$this->data['News']['image']  = $filename['name'];
			if ($this->News->save($this->data)) {
				$this->Session->setFlash(__('Đã lưu.', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Thông tin không được lưu. Vui lòng thử lại.', true));
			}
		}
		$catenews = $this->News->Catenews->find('list');
		$this->set(compact('catenews'));
	}

	 function admin_edit($id = null) {
		$files = $this->News->find('list',array(
			'conditions'=>array('News.id'=>$id),
			'fields'=>'image')
		);
		$file ='';
		$file = "files" . DS . "uploads/news" . DS .$files[$id];
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Không tồn tại bài viết này.', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			$this->data['News']['image'] = $files[$id];
            if ($data = $this->Uploader->upload('image')) {
				$tmpname  = $data['name'];
				if(is_file($file)){
					unlink($file);
				}
				$this->data['News']['image'] = $tmpname;
            }
			if ($this->News->save($this->data)) {
				$this->Session->setFlash(__('Đã lưu.', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Thông tin không được lưu. Vui lòng thử lại.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->News->read(null, $id);
		}
		$catenews = $this->News->Catenews->find('list');
		$this->set(compact('catenews'));
		//$this->set('model',$this->uses[0]);
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Không tồn tại bài viết này !', true));
			$this->redirect(array('action'=>'index'));
		}
		if($id){
			$files = $this->News->find('first',array(
			'conditions'=>array('News.id'=>$id),
			'fields'=>'image')
		);
		$file = "files/uploads/news/".$files['News']['image'];
			if(is_file($file)){
				unlink($file);
			}
		}
		if ($this->News->delete($id)) {
			$this->Session->setFlash(__('Đã xóa !', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Có lỗi xảy ra. Chưa xóa được bài viết !', true));
		$this->redirect(array('action' => 'index'));
	}
	function admin_mutildelete($str = null){
        if($str){
            $arrid=explode(',',$str);
        }else{
    		$this->Session->setFlash(__('Có lỗi xảy ra. Chưa xóa được bài viết !', true));
    		$this->redirect(array('action' => 'index'));
        }
         foreach($arrid as $item){
			if($item != null){
				$files = $this->News->find('first',array(
				'conditions'=>array('News.id'=>$item),
				'fields'=>'image')
				);
				$file = "files/uploads/news/".$files['News']['image'];
				if(is_file($file)){
					unlink($file);
				}
			}
    		$this->News->delete($item);
         }
		$this->Session->setFlash(__('Đã xóa !', true));
		$this->redirect(array('action' => 'index'));
    }
	function delfile($id = null){
		$files = $this->News->find('first',array(
			'conditions'=>array('News.id'=>$item),
			'fields'=>'image')
			);
		$file = "files/uploads/news/".$files['News']['image'];
		if(is_file($file)){
			unlink($file);
		}
		$this->News->query("Update tblnews set image = '' where id='".$id."'");
    }
    function printpage($m=null,$id = null){
    	//$this->layout = 'default';
    	if (!$id) {
			$this->Session->setFlash(__('Không tồn tại bài viết này.', true));
			$this->redirect(array('action' => 'index'));
		}
		$rec = $this->$m->read(null, $id);
 		$this->set('rec',$rec);
    }

	function _validate_form_items()
	{
	  // global $msg_min_chars, $msg_max_chars;
	    $msg_min_chars = 10;
		$msg_max_chars = 250;
	   $msg_chars = "{".$msg_min_chars.",".$msg_max_chars."}";

	   $form_items = array(

		   "name"  => array(
						   "regex" => "/^([a-zA-Z '-]+)$/",
						   "error" => "Tên không đúng định dạng",
						   ),
			"email" => array(
						   "regex" =>
							"/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/",
						   "error" => "email không đúng định dạng",
						   ),
		   "message" => array(
						   "regex" => "/.*/",
						   "error" => "Lời nhắn của bạn quá ngắn hoặc vượt quá $msg_max_chars ký tự",
						   ),
	   );

	   global $errors;

		if(!preg_match($form_items["name"]["regex"], $this->data['News']["name"]))
			$errors[] = $form_items["name"]["error"];

		if(!preg_match($form_items["email"]["regex"], $this->data['News']["email"]))
			$errors[] = "your ".$form_items["email"]["error"];

		if(!preg_match($form_items["email"]["regex"], $this->data['News']["friend1"]))
			$errors[] = "Friend 1 ".$form_items["email"]["error"];

		if(strlen(trim($this->data['News']["message"])) < $msg_min_chars || strlen(trim($this->data['News']["message"])) >  $msg_max_chars )
			$errors[] = $form_items["message"]["error"];

		if(trim($this->data['News']["friend2"]) != "")
		{
			if(!preg_match($form_items["email"]["regex"], $this->data['News']["friend2"]))
				$errors[] = "Friend 2 ".$form_items["email"]["error"];
		}

		if(trim($this->data['News']["friend3"]) != "")
		{
			if(!preg_match($form_items["email"]["regex"], $this->data["friend3"]))
				$errors[] = "Friend 3 ".$form_items["email"]["error"];
		}
		//debug($errors);
	   return count($errors);
	}

	function _email($from, $from_name, $to, $message)
	{
		//header("Location: thankyou.html");return;
		$headers ="";
		$headers .= "From: ".$from."\r\n";
		$headers .= "Content-type: text/plain; charset=utf-8";

		$your_domian_name = $this->webroot;
		//edit what you want your vistors to see in their email here
		$subject = $from_name." mời bạn xem một bài viết từ $your_domian_name";
		$your_message = "Chào !\r\n";
		$your_message.= ucfirst($from_name);
		$your_message.= " đã mời bạn xem một bài iết từ trang $your_domian_name\r\n";
		$your_message.= "Với lời nhắn sau :\n\r";

		$message=$your_message.stripslashes($message);

		if (@mail($to,$subject,$message,$headers) ) {
			return true;
		} else {
			return false;
		}
	}

	function print_error($errors)
	{

		foreach($errors as $error)
		{
			$err.=$error."<br/>";
		}

		echo
		 "<div style=\"border:1px red solid; font-size:14px; font-weight:normal; color:red; margin:10px; padding:10px;\">
			$err
		 <div>";

	}

	function send()
	{
		$this->autoRender=false;
		//debug($this->data);
		$from_name = $this->data['News']['name'];
		$from_email = $this->data['News']['email'];

		$to = $this->data['News']['email'].",".$this->data['News']['friend1'].",".$this->data['News']['friend2'].",".$this->data['News']['friend3'];
		$message = $this->data['News']['message'];

		$error_count = $this->_validate_form_items();
		//echo $error_count;
		if($error_count == 0)
		{
			//debug($from_email);
			if($this->_email($from_email, $from_name, $to, $message))
				echo "Đã gửi thành công cho bạn bè!";
			else
			{
				global $errors;
				$errors[] = "Có lỗi xảy ra. Không thể gửi mail.";
			}
		}


	}
}
?>